const Controller = require('egg').Controller;
class HomeController extends Controller {
  //登录
  async login() {
    const { ctx, service, app } = this
    try {
      const { username, password } = ctx.request.body
      const results = await service.home.isLogin({
        username,
        password
      })
      if (results.isExists) {
        const token = app.jwt.sign(username, app.config.jwt.secret);
        this.ctx.body = {
          code: 200,
          msg: "登录成功",
          token
        }
      } else {
        this.ctx.body = {
          code: 0,
          msg: "登录失败"
        }
      }
    } catch (e) {
      ctx.body = {
        code: 0,
        message: e.message
      }
    }
  }
  //获取用户列表
  async getUserList() {
    const { ctx, service } = this
    try {
      console.log(ctx.query.roles)
      let result = await service.home.getList(ctx.query.roles)
      ctx.body = result
    } catch (e) {
      ctx.body = {
        code: 0,
        message: e.message
      }
    }

  }
  //退出登录
  async logout() {
    const { ctx } = this
    try {
      ctx.body = {
        code: 200,
        message: "退出登录"
      }
    } catch (e) {
      ctx.body = {
        code: 0,
        message: e.message
      }
    }
  }
  //动态路由
  async info() {
    const { ctx } = this;
    ctx.body = {
      name: `hello ${ctx.params.id}`,
    };
  }
  //注册 
  async register() {
    const { ctx, service } = this
    const { username, password, role } = ctx.request.body
    const results = await service.home.checkUser({
      username
    })
    if (results.code === 0) {
      this.ctx.body = results
    } else {
      if (results.isExists) {
        this.ctx.body = {
          code: 10001,
          msg: '此用户名已被占用'
        }
      } else {
        const register = await service.home.reigster({ username, password, role })
        ctx.body = register
      }
    }
  }
  async getInfo() {
    const { ctx, app } = this;
    try {
      let token = ctx.query.token
      let username = app.jwt.verify(token, this.app.config.jwt.secret)
      let result = await ctx.service.home.getInfo({
        username
      })
      ctx.body = result
    } catch (e) {
      ctx.body = {
        code: 0,
        message: e.message
      }
    }
  }
  async index() {
    const { ctx } = this;
    ctx.body = 'hi, egg';
  }
}

module.exports = HomeController;
